package com.yehun.config;


import org.springframework.format.Formatter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class SpringDateFormatter implements Formatter<Date> {

    private String dateTimePattern; //yyyy-MM-dd HH:mm:ss
    public void setDateTimePattern(String dateTimePattern) {
        this.dateTimePattern = datePattern;
    }
    private String datePattern; //yyyy-MM-dd
    public void setDatePattern(String datePattern) {
        this.datePattern = datePattern;
    }
    private String timePattern; //HH:mm:ss
    public void setTimePattern(String timePattern) {
        this.timePattern = timePattern;
    }

    @Override
    public String print(Date arg0, Locale arg1) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Date parse(String text, Locale locale) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat(this.dateTimePattern);
        Date date = null;
        try {
            if(!"".equals(text) && null != text)
                date = format.parse(text);
        } catch (Exception e) {
            try {
                format = new SimpleDateFormat(datePattern);
                date = format.parse(text);
            } catch (Exception ex) {
                format = new SimpleDateFormat(timePattern);
                date = format.parse(text);
            }
        }
        return date;
    }

}
